<template>
  <div class="chapter-mgr">
    <h2>章节管理</h2>
    <el-button type="primary" @click="showAddDialog">添加章节</el-button>
    
    <el-tree
      :data="chapterTree"
      :props="defaultProps"
      show-checkbox
      node-key="id"
      default-expand-all
      :expand-on-click-node="false">
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span class="tree-actions">
            <el-button
              type="text"
              size="mini"
              @click="() => viewChapter(data.id)">查看</el-button>
            <el-button
              type="text"
              size="mini"
              @click="() => editChapter(data.id)">编辑</el-button>
            <el-button
              type="danger"
              size="mini"
              @click="() => deleteChapter(data.id)">删除</el-button>
          </span>
        </span>
      </template>
    </el-tree>
    
    <!-- 添加/编辑章节对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="chapterForm" label-width="120px">
        <el-form-item label="章节标题">
          <el-input v-model="chapterForm.chaTitle"></el-input>
        </el-form-item>
        <el-form-item label="章节索引">
          <el-input-number v-model="chapterForm.chaIndex"></el-input-number>
        </el-form-item>
        <el-form-item label="视频URL">
          <el-input v-model="chapterForm.videoUrl"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveChapter">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { classApi } from '@/api/class'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

const chapterTree = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('添加章节')
const isEdit = ref(false)
const chapterForm = reactive({
  chaTitle: '',
  chaIndex: 0,
  videoUrl: ''
})

const defaultProps = {
  children: 'children',
  label: 'chaTitle'
}

// 获取章节树
const fetchChapterTree = async () => {
  try {
    const res = await classApi.getNestedTreeList(101) // 教师ID
    chapterTree.value = formatChapterTree(res.data)
  } catch (error) {
    ElMessage.error('获取章节树失败')
    console.error(error)
  }
}

// 格式化章节数据
const formatChapterTree = (list) => {
  return list.map(item => ({
    id: item.id,
    chaTitle: item.chaTitle,
    children: item.children || []
  }))
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加章节'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(chapterForm, {
    chaTitle: '',
    chaIndex: 0,
    videoUrl: ''
  })
}

// 查看章节
const viewChapter = (id) => {
  router.push(`/class/chapters/${id}`)
}

// 编辑章节
const editChapter = (id) => {
  dialogTitle.value = '编辑章节'
  isEdit.value = true
  // 实际项目中应该先获取章节详情
  resetForm()
  chapterForm.chaTitle = '示例章节' // 这里应该是API获取的真实数据
  dialogVisible.value = true
}

// 删除章节
const deleteChapter = async (id) => {
  try {
    await classApi.deleteChapter(id)
    ElMessage.success('删除成功')
    fetchChapterTree()
  } catch (error) {
    ElMessage.error('删除失败')
    console.error(error)
  }
}

// 保存章节
const saveChapter = async () => {
  try {
    const data = {...chapterForm}
    if (isEdit.value) {
      await classApi.updateChapter(data)
    } else {
      await classApi.saveChapter(data)
    }
    ElMessage.success(isEdit.value ? '更新成功' : '保存成功')
    dialogVisible.value = false
    fetchChapterTree()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '保存失败')
    console.error(error)
  }
}

fetchChapterTree()
</script>

<style scoped>
.chapter-mgr {
  padding: 20px;
}
.custom-tree-node {
  display: flex;
  justify-content: space-between;
  width: 100%;
}
.tree-actions {
  display: flex;
  gap: 5px;
}
</style>